<template>
  <div>
    <KDialog v-model:showDialog="submitDialog.show">
        <template #header>
            <div style="font-size:24px;font-family: 'Roboto Slab', serif;">通知 INFO</div>
        </template>
        <div style="padding:20px;">
            <div style="font-size : 21px;" align="center"> 
                你确定要发布吗 ? 请确保所有同学都加入小组后再点击发布！
            </div>
        </div>
        <div align="center">
            <button style="margin:10px;" class="button primary" @click="submitDialog.confirm">确定</button>
            <button style="margin:10px;" class="button" @click="submitDialog.show = false">取消</button>
        </div>
    </KDialog>

    <!-- 提示去创建小组的对话框 -->
    <KDialog v-model:showDialog="gotoCreate.show">
      <template #header>
        <div style="font-size: 20px; font-family: 'Roboto Slab', serif">
          提示 INFO
        </div>
      </template>
      <div align="center">
        <div style="font-size:18px;margin:30px 10px;">你还未创建小组，是否现在去创建？</div>
        <div align="right">
          <button
            class="button primary"
            style="margin: 0 10px"
            @click="gotoCreate.handleConfirm"
          >
            确定
          </button>
          <button @click="gotoCreate.show = false" style="margin: 0 10px">
            取消
          </button>
        </div>
      </div>
    </KDialog>
    
    <KCard>
        <template #header>
            <div style="padding:20px 0 0 0;font-size:20px;">
                <KTitle3>发布作业 publish</KTitle3>
            </div>
        </template>
        <section style="padding:10px 0 20px 0;">
        <div>
            <label for="homeworkname">
            <div class="InputLabel">作业名 Homework Name</div>
            <input
                type="text"
                class="MyInput"
                style="margin:10px;width: 50% !important; border-radius: 0.5em !important"
                name="homeworkname"
                v-model="form.homeworkName"
            />
            </label>
        </div>

        <div>
            <label for="submittype">
            <div class="InputLabel">提交类型 Submit Type</div>
            <el-cascader
                class="MySelect"
                v-model="form.submitType.value"
                :options="form.submitType.options"
                @change="form.submitType.handleChange"
                name="submittype"
            />
            </label>
        </div>
        <div>
            <label for="subject">
            <div class="InputLabel" name="subject">
                学科与项目 Subject & Project
            </div>
            <input
                type="text"
                class="MyInput"
                style="margin:10px;width: 50% !important; border-radius: 0.5em !important"
                name="subject"
                v-model="form.subject"
            />
            </label>
        </div>
        <br />

        <div style="display: flex">
            <label
            class="InputLabel"
            :style="`font-size: 18px;margin:0 10px 0 0;color:${
                form.allowDelay ? 'var(--mainColor)' : 'black'
            }`"
            >
            允许延迟提交 Allow Delay
            </label>
            <el-tooltip
            content="勾选此项, 那么在截至日期结束后, 同学们依旧可以提交"
            placement="top"
            effect="dark"
            >
            <el-switch v-model="form.allowDelay" />
            </el-tooltip>
        </div>
        <br />

        <div style="display: flex">
            <label class="InputLabel" style="font-size: 18px; margin: 10px 10px 10px 0px">
            截止日期 Deadlines
            </label>
            <el-date-picker
              v-model="form.deadtime"
              type="datetime"
              placeholder="选择截止日期和时间"
              :time-arrow-control="true"
            />
            <!-- TODO 如果需要修改时区，请修改这里 -->
        </div>
        <br />

        <div style="display: flex">
            <label for="chooseGroup" style="display: flex">
              <div class="InputLabel" style="font-size:18px;margin:10px 0;">选择小组 Choose Group</div>
              <el-tooltip
              :content="`
              需要注意，请确保所有您希望参与作业的成员都加入对应的小组后再创建作业
              创建作业后加入小组的成员将看不到创建的作业
              `"
              placement="top"
              effect="dark"
              >
              <div class="icon solid fa-question-circle"></div></el-tooltip>
              <el-cascader
                  v-model="createdGroup.selvalue"
                  :options="createdGroup.options"
                  @change="createdGroup.handleChange"
                  name="chooseGroup"
              />
              
            </label>
        </div>
        <br>
        <div>
            <label for="submittype">
            <div class="InputLabel">备注* DESC (选填)</div>
            <textarea 
            cols="30" 
            rows="3" 
            v-model="form.desc"
            :style="`resize:${config.textAreaMove ? 'both' : 'none'}`"
            ></textarea>
            </label>
        </div>
        </section>
    </KCard>

    
    <KBlock lines="2"></KBlock>

    <div class="InputLabel" align="center">
        <button 
            class="button primary"
            @click="submit"
        >
            发布 Publish
        </button>
    </div>

    <KBlock lines="3"></KBlock>

  </div>
</template>



<script>
import { reactive, onMounted, computed } from "vue";
import { useStore } from "vuex";
import { useRouter } from "vue-router"
import { ElNotification, ElLoading } from "element-plus";
import { formatTime } from "@/hook/format"


export default {
  name: "New",
  setup() {
    let store = useStore()
    let router = useRouter()

    onMounted(() => {
      const loading = ElLoading.service({
        lock: true,
        text: '正在拉起您的信息中...',
        background: 'rgba(0, 0, 0, 0.8)',
        customClass: "MyLoading"
      })
      store.dispatch("groupCreateNum").then(function () {
        if (store.state.group.groupCreateNum) {
          let start = 0;
          let end = Math.min(store.state.group.groupCreateNum, 100);
          store.dispatch("groupCreated", { start, end }).then(function () {
            loading.close()
            if (store.state.group.groupCreated.length > 0) {} 
            else {ElNotification({title: "Oops", message: "拉去初始化列表失败，错误信息: " + store.state.error})}
          });
        } 
        else {
          loading.close()
          let message;
          if (store.state.group.groupCreateNum == 0) {
            gotoCreate.show = true
            return
          }
          else {
            message = "不知道为啥，请求您创建的小组数量数量时出错了，错误信息: " + store.state.error
          }
          ElNotification({title: "Oops", message: message});
          return;
        }
      });
    });

    let config = reactive({
      textAreaMove : store.state.textAreaMove,
    })

    let form = reactive({
      homeworkName: "",
      submitType: {
        value: "",
        options: [
          { value: "zip", label: "压缩包 (*.zip *.rar)" },
          { value: "source", label: "代码源文件 (*.py *.cpp *.c *.java *.v *.go *.php *.js *.ts *.sql)",},
          { value: "word", label: "word文档 (*.doc *docx)" },
          { value: "ppt", label: "幻灯片 (*.ppt *pptx *keynote)" },
          { value: "pdf", label: "PDF (*.pdf)" },
          { value: "data", label: "数据集 (*.csv *.tsv *.txt *.json *.yaml *.yml)" },
          { value: "picture", label: "图像 (*.png *.jpg *.jepg *svg *esp *pdf)",},
          { value: "model", label: "模型 (*.pth *.pkl *.caffe *.onnx)" },
          { value: "config", label: "配置文件 (*.json *.yaml *.yml *.protcbuf)",},
        ],
        handleChange() {
          
        },
      },
      // 提交后应该更新首页的倒计时
      subject: "",
      allowDelay: false,
      deadtime : "",
      desc : ""
    });

    let submitDialog = reactive({
        show : false,
        confirm() {
            let name = form.homeworkName.trim()
            let type = form.submitType.value[0]
            let desc = form.desc.trim()
            let subject = form.subject.trim()
            let endtime = form.deadtime
            let canSubmitAfterEnd = form.allowDelay
            let groupID = createdGroup.selvalue[0]

            const loading = ElLoading.service({
              lock: true,
              text: '正在提交请求中...',
              background: 'rgba(0, 0, 0, 0.8)',
              customClass: "MyLoading"
            })


            store.dispatch("addHomework", {name, type, desc, subject, endtime, canSubmitAfterEnd, groupID}).then(function() {
              if (store.state.opSuccess === true) {
                store.state.opSuccess = undefined
                loading.close()
                ElNotification({title : "发布成功！", message : "别忘了去首页看看最新的ddl"})
                submitDialog.show = false
              }
              else {
                loading.close()
                ElNotification({title : "Oops", message : "发布失败了，错误信息: " + store.state.error})
              }
            })
        }
    })

    let createdGroup = reactive({
      selvalue : "",
      options : computed(() => {
        let groups = store.state.group.groupCreated, res = []
        for (let i = 0; i < groups.length; ++ i) {
          res.push({
            value : groups[i].id, 
            label : `${groups[i].name}(ID ${groups[i].id})`
          })
        }
        return res
      }),

      handleChange() {
        // console.log(createdGroup.selvalue[0])
      }
    })

    let gotoCreate = reactive({
      show : false,
      handleConfirm() {
        router.push("/newgroup")
        gotoCreate.show = false
      },
      handleCancel() {
        gotoCreate.show = false
      }
    })


    function submit() {
      // check
      let name = form.homeworkName.trim()
      let type = form.submitType.value
      let subject = form.subject.trim()
      if (form.deadtime.length == 0) {
        ElNotification({title: "Wrong!", message: "您貌似还有信息没有填完"})
        return
      }
      let endtime = formatTime(form.deadtime, "yyyy-MM-ddTHH:mm:ss+08:00")
      let groupID = createdGroup.selvalue
      
      if (name.length == 0 || subject.length == 0 || endtime.length == 0) {
        ElNotification({title: "Wrong!", message: "您貌似还有信息没有填完"})
        return
      }
      if (name.includes(" ") || subject.includes(" ") || endtime.includes(" ")) {
        ElNotification({title: "Wrong!", message: "所填字段不能有空格！"})
        return       
      }
      if (type) {}
      else {
        ElNotification({title: "Wrong!", message: "请选择提交类型！"})
        return
      }
      if (groupID) {}
      else {
        ElNotification({title: "Wrong!", message: "请选择小组！"})
        return
      }
      // 输入的时间必须比当前时间后
      let curtime = new Date()
      
      curtime = formatTime(curtime, "yyyy-MM-ddTHH:mm:ss+08:00")
      if (curtime > endtime) {
        ElNotification({title: "Wrong!", message: "你发布的截止时间在过去，你是想让熵增颠倒吗？"})
        return
      }
      submitDialog.show = true;
    }

    return {
      form,
      submit,
      submitDialog,
      gotoCreate,
      createdGroup,
      config
    };
  },
};
</script>

<style>
.InputLabel {
  font-size: 20px;
  font-family: "Roboto Slab", serif;
}

.MySelect {
  width: 40% !important;
  font-family: "Roboto Slab", serif;
  font-size: 16px;
  text-align: center;
  border-radius: 3em !important;
  transition: all var(--focusTime) linear;
  -webkit-transition: all var(--focusTime) linear;
  -moz-transition: all var(--focusTime) linear;
}

el-time-picker button {
  border: 0ch !important;
}

.el-time-panel__footer {
  height: fit-content !important;
}

.el-time-panel__footer button {
  font-size : 8px;
}

.el-popper {
  font-family: "Roboto Slab", serif;
}

.el-popper button {
  font-size : 15px !important;
  border-radius: 1.5em !important;
  padding: 0 10px;
  box-shadow: 0 0 0 0 !important;
  margin: 1px;
}

.el-picker-panel__footer button {
  font-size : 8px !important;
  border-radius: 3em !important;
  padding: 20px !important;
  transition: all .3s linear;
  -moz-transition: all .3s linear;
  -webkit-transition: all .3s linear;
}

.el-picker-panel__footer button:hover {
  background-color: var(--mainColor);
  color: white;
  box-shadow: 0 0 8px 3px var(--mainColor) !important;
  transition: all .3s linear;
  -moz-transition: all .3s linear;
  -webkit-transition: all .3s linear;
}
</style>